package com.example.leetdemo.plan1;

import java.util.*;

public class Sword007 {

    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> list = new ArrayList<>();
        if (nums[0] == nums[nums.length - 1] && nums[0] == 0) {
            list.add(Arrays.asList(0,0,0));
            return list;
        }
        Set<Integer> used = new HashSet<>();
        Set<String> indexSet = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (used.contains(nums[i])) {
                continue;
            } else {
                used.add(nums[i]);
            }
            int target = -nums[i];
            int p = i + 1, q = nums.length - 1;
            while (p < q) {
                int sum = nums[q] + nums[p];
                if (sum > target) {
                    q--;
                } else if (sum < target) {
                    p++;
                } else {
                    int[] t = new int[]{nums[p], nums[i], nums[q]};
                    Arrays.sort(t);
                    String str = "" + t[0] + t[1] + t[2];
                    if (!indexSet.contains(str)) {
                        indexSet.add(str);
                        list.add(Arrays.asList(nums[p], nums[i], nums[q]));
                    }
                    p++;
                }

            }
        }
        return list;
    }

    public static void main(String[] args) {
        Sword007 sword007 = new Sword007();
        System.err.println(sword007.threeSum(new int[] {-2,0,1,1,2}));
    }
}
